﻿// directive to handle binding from upload input box
angular.module('app.common').directive("uploadModel", [function () {
	return {
		restrict: 'A',
		scope: {
			uploadModel: "="
		},
		link: {
			post: function postLink(scope, element, attributes) {
				var elm = element;
				// when the change event is raised
				element.bind("change", function (changeEvent) {
					// set the upload model value to the files
					scope.$apply(function () {
						scope.uploadModel = changeEvent.target.files;
					});
				});
				// when the upload model changes, update the element's value
				scope.$watch('uploadModel', function (newValue) {
					// throws an exception but still works, not sure why
					try {
						if (newValue == elm.val())
							return;
						elm.val(newValue);
					}
					catch (e) { }
				}, true);
			}
		}
	}
}]);